package oss

import (
	"encoding/json"
	"gitee.com/alex_li/zangjingge/internal/db/rdb"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/app-starter/persistence"
	"github.com/lishimeng/go-log"
	"os"
	"path"
)

func ProcSaveFile(fileCode string, bucketCode string, tempFileId string) (err error) {

	meta, err := GetTempFileMeta(tempFileId)
	if err != nil {
		log.Info(err)
		return
	}
	var docInfo rdb.DocInfo
	var bucket rdb.BucketInfo
	err = app.GetOrm().Transaction(func(tx persistence.TxContext) (er error) {
		er = tx.Context.QueryTable(new(rdb.DocInfo)).Filter("Code", fileCode).One(&docInfo)
		if er != nil {
			log.Info(er)
			return
		}
		er = tx.Context.QueryTable(new(rdb.BucketInfo)).Filter("Code", bucketCode).One(&bucket)
		if er != nil {
			log.Info(er)
			return
		}
		return
	})
	if err != nil {
		log.Info(err)
		return
	}

	relPath, _, err := saveFile(docInfo, bucket, meta)
	if err != nil {
		log.Info(err)
		return
	}
	docInfo.Digest = meta.Md5 + meta.Sha256
	docInfo.Bucket = bucketCode
	docInfo.FilePath = relPath
	docInfo.FileSize = meta.FileSize
	docInfo.Status = int(rdb.DocInfoStateSave)
	_, err = app.GetOrm().Context.Update(&docInfo)
	if err != nil {
		log.Info(err)
		return
	}
	return
}

func ProcRemoveDocInfo(docCode string) {
	var docInfo rdb.DocInfo
	docInfo.Code = docCode
	_, err := app.GetOrm().Context.Delete(&docInfo, "code")
	if err != nil {
		log.Info(err)
	}
}

func GetTempFileMeta(tempId string) (meta TempFileMeta, err error) {
	p := GetMetaFilePath(path.Join(GetTempRootFolder(), tempId))
	bs, err := os.ReadFile(p)
	if err != nil {
		return
	}
	err = json.Unmarshal(bs, &meta)
	return
}
